package com.dokimall.ware.service.impl;

import com.dokimall.common.constant.WareConstant;
import com.dokimall.ware.entity.PurchaseDetailEntity;
import com.dokimall.ware.service.PurchaseDetailService;
import com.dokimall.ware.service.WareSkuService;
import com.dokimall.ware.vo.MergeVo;
import com.dokimall.ware.vo.PurchaseDoneVo;
import com.dokimall.ware.vo.PurchaseItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dokimall.common.utils.PageUtils;
import com.dokimall.common.utils.Query;

import com.dokimall.ware.dao.PurchaseDao;
import com.dokimall.ware.entity.PurchaseEntity;
import com.dokimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getUnreceiveList(Map<String, Object> params) {

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void purchaseMerge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        // 如果没有指定采购单，进行新建
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // 合并整单前判断采购需求的状态是否能够操作
        Long[] items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        Collection<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(Arrays.asList(items));

        List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream()
                .filter((item)->{
                    if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()
                            || item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()){
                        return true;
                    }else {
                        return false;
                    }
                })
                .map((item) -> {
            item.setPurchaseId(finalPurchaseId);
            item.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return item;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(collect);

        // 修改时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        // 1 更新采购单状态
        List<PurchaseEntity> purchaseEntityList = this.listByIds(ids).stream().filter((purchase) -> {
            // 判断状态是否为新建或者已分配
            if (purchase.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || purchase.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map((purchase) -> {
            purchase.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchase.setUpdateTime(new Date());
            return purchase;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntityList);

        // 更新对应采购单的采购需求状态
        purchaseEntityList.forEach((item)->{
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.getPurchaseDetailList(item.getId());
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map((purcdet) -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(purcdet.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        });

    }

    @Override
    public void done(PurchaseDoneVo doneVos) {

        // 改变采购项的状态
        Boolean flag = true; // 当有一个采购项采购失败，flag为false采购单状态对应失败
        List<PurchaseItemVo> items = doneVos.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        for(PurchaseItemVo item : items){
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                // 入库失败
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else {
                // 入库完成
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode());
                //添加到库存
                PurchaseDetailEntity detailServiceById = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addToWare(detailServiceById.getSkuId(),detailServiceById.getWareId(),detailServiceById.getSkuNum());

            }
            purchaseDetailEntity.setStatus(item.getStatus());
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntities.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        // 改变采购单的状态
        Long id = doneVos.getId();//采购单的ID
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISHED.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}